<template>
  <div style="display: inline-block;">
    <el-dialog
      :visible.sync="dialog"
      :close-on-click-modal="false"
      :before-close="cancel"
      :title="title"
      append-to-body
      width="475px"
      @close="cancel"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        size="small"
        label-width="88px"
      >
        <el-form-item label="新邮箱" prop="email">
          <el-input
            v-model="form.email"
            auto-complete="on"
            style="width: 206px;"
          />
          <el-button
            :loading="codeLoading"
            :disabled="isDisabled"
            size="small"
            @click="sendCode"
            style="margin:0 0 0 20px"
            >{{ buttonName }}</el-button
          >
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="form.code" style="width: 320px;" />
        </el-form-item>
        <el-form-item label="当前密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            style="width: 320px;"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="info" @click="cancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="doSubmit"
          >确认</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions, mapGetters } from "vuex";
import { validEmail } from "@/utils/validate";
export default {
  props: {
    email: {
      type: String,
      required: true
    }
    // getUserInfo: {
    //   type: Function
    // }
  },
  data() {
    const validMail = (rule, value, callback) => {
      if (value === "" || value === null) {
        callback(new Error("新邮箱不能为空"));
      } else if (value === this.email) {
        callback(new Error("新邮箱不能与旧邮箱相同"));
      } else if (validEmail(value)) {
        callback();
      } else {
        callback(new Error("邮箱格式错误"));
      }
    };
    return {
      loading: false,
      dialog: false,
      title: "修改邮箱",
      form: { password: "", email: "", code: "" },
      user: { email: "", password: "" },
      codeLoading: false,
      buttonName: "获取验证码",
      isDisabled: false,
      time: 60, // 重发倒计时
      rules: {
        password: [
          { required: true, message: "当前密码不能为空", trigger: "blur" }
        ],
        email: [{ required: true, validator: validMail, trigger: "blur" }],
        code: [{ required: true, message: "验证码不能为空", trigger: "blur" }]
      },
      sendTimes: 0, // 修改时间戳（单位"毫秒"）
      sentTimes: 0, // 初始时间戳（单位"毫秒"）
      Expiration: 10 // 过期时间（单位"分"）
    };
  },
  methods: {
    ...mapActions("user", ["updateEmail", "sendEmail"]),
    cancel() {
      this.resetForm();
    },
    sendCode() {
      if (this.form.email && this.form.email !== this.email) {
        this.codeLoading = true; // 正在发送加载圈
        this.buttonName = "验证码发送中";
        const _this = this;
        this.sendEmail(this.form.email)
          .then(res => {
            this.sentTimes = +new Date(); // 当前时间总的毫秒数
            sessionStorage.setItem("MixCode", res.mixCode); // 前端缓存验证码
            this.$message({
              showClose: true,
              message: `发送成功，验证码有效期${this.Expiration}分钟`,
              type: "success"
            });
            this.codeLoading = false; // 关闭正在加载圈
            this.isDisabled = true; // 禁用按钮
            this.buttonName = this.time-- + "秒后重新发送";
            this.timer = window.setInterval(function() {
              _this.buttonName = _this.time + "秒后重新发送";
              --_this.time; // 倒计时
              if (_this.time < 0) {
                _this.buttonName = "重新发送"; // 按钮文字
                _this.time = 60; // 重置倒计时60秒
                _this.isDisabled = false; //关闭按钮禁用
                window.clearInterval(_this.timer); // 倒计时完成，清除定时器
              }
            }, 1000);
          })
          .catch(err => {
            // 捕捉错误
            this.resetForm();
            this.codeLoading = false;
            console.log(err.response.data.message);
          });
      }
    },
    doSubmit() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.code === sessionStorage.getItem("MixCode")) {
            // 输入的验证码 === 发送的过来的验证码
            this.sendTimes = +new Date(); // 记录发送修改的时间戳
            if (
              ((this.sendTimes - this.sentTimes) / 1000 / 60) % 60 >
              this.Expiration
            ) {
              // 过期 => (发送修改时间-验证码初始时间) 转化分钟单位后 > 过期时间(时间单位：分)
              this.form.code = ""; // 清除输入的验证码
              this.$notify({
                title: "验证码已过期，请重新发送",
                type: "warning",
                duration: 1500
              });
              return;
            } else {
              // 验证码未过期发送修改请求
              this.loading = true; // 加载开启
              this.updateEmail({ form: this.form, email: this.email })
                .then(res => {
                  if (res.code === 200) {
                    this.loading = false; // 加载关闭
                    this.resetForm(); // 重置
                    this.$parent.getUserInfo(); // 触发父组件上的刷新用户信息事件
                    // this.getUserInfo(); // 触发父组件上的刷新用户信息事件
                    this.$notify({
                      title: res.msg,
                      type: "success",
                      duration: 1500
                    });
                  }
                })
                .catch(err => {
                  this.loading = false; // 加载关闭
                  console.log(err.response.data.message);
                });
            }
          } else {
            // 输入的验证码与发送的验证码不相同
            this.$notify({
              title: "验证码错误，请重新输入验证码",
              type: "success",
              duration: 1500
            });
            return;
          }
        } else {
          return false;
        }
      });
    },
    resetForm() {
      this.dialog = false; // 关闭弹窗
      this.$refs["form"].resetFields(); // elementUI重置表单
      window.clearInterval(this.timer); // 清除等待时间的定时器
      this.time = 60; //  重置获取等待时间
      this.buttonName = "获取验证码"; // 重置按钮文字
      this.isDisabled = false; // 关闭按钮禁用
      this.form = { password: "", email: "", code: "" }; // 清空表单
      sessionStorage.removeItem("MixCode"); // 清除session缓存的验证码
      this.sentTimes = 0; // 重置初始时间戳
      this.sendTimes = 0; // 重置修改时间戳
    }
  }
};
</script>

<style scoped></style>
